package cn.cpf.app.gobang.entity;

import cn.cpf.app.gobang.modal.Place;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

public class SortedPlaces {

    private SortedSet<ScorePlace> commonScorePlace;

    public boolean hasData() {
        return commonScorePlace != null;
    }

    public void addOrInit(Place place, int score) {
        if (commonScorePlace == null) {
            commonScorePlace = new TreeSet<>((o1, o2) -> {
                // treeSet 里面如果, 结果等于0 则相当于会一个覆盖另一个.
                int r = o2.score - o1.score;
                if (r == 0) {
                    r = o2.place.x - o1.place.x;
                }
                if (r == 0) {
                    r = o2.place.y - o1.place.y;
                }
                return r;
            });
        }
        commonScorePlace.add(new ScorePlace(place, score));
    }

    /**
     * @return 排序后的位置
     */
    public List<Place> getSortedPlaces() {
        List<Place> places = new ArrayList<>(commonScorePlace.size());
        for (ScorePlace item : commonScorePlace) {
            places.add(item.place);
        }
        return places;
    }

    private static class ScorePlace {
        public final Place place;
        public final int score;

        public ScorePlace(Place place, int score) {
            this.place = place;
            this.score = score;
        }
    }
}
